<template>
  <div>
    <x-Table
      :loading="loading"
      :table-data="tableData"
      :options-data="options"
      :pagination="pagination"
      :rule-form="ruleForms"
      @handleAdd="handleAdd"
      @handlePaginationCurrentChange="handlePaginationCurrentChange"
      @handlePaginationSizeChange="handlePaginationSizeChange"
      @handleHeardDel="handleHeardDel"
      @searchForm="searchForm"
      @resetForm="resetForm"
      @onUploadSuccess="onUploadSuccess"
      @onUploadError='onUploadError'
      @downloadTemplate="downloadTemplate"
    >
    </x-Table>
    <!--    弹窗区域-->
    <el-dialog
      style="z-index: 500;!important;"
      v-dialog-drag
      :title="alertTitle"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="60%"
    >

      <el-tabs v-model="$store.state.exam.activeName" @tab-click="handleClick">
        <el-tab-pane :disabled="$store.state.exam.edit.name != '单选题' && $store.state.exam.edit.name  != ''   "
                     label="单选题"
                     name="单选题">
          <dan v-if="$store.state.exam.activeName == '单选题' " @onSubmit="onSubmit" @onClose="onClose"/>
        </el-tab-pane>
        <el-tab-pane :disabled="$store.state.exam.edit.name  != '多选题' && $store.state.exam.edit.name  != ''  "
                     label="多选题"
                     name="多选题">
          <duo v-if="$store.state.exam.activeName == '多选题' " @onSubmit="onSubmit" @onClose="onClose"/>
        </el-tab-pane>
        <el-tab-pane :disabled="$store.state.exam.edit.name  != '判断题' && $store.state.exam.edit.name  != ''  "
                     label="判断题"
                     name="判断题">
          <pan v-if="$store.state.exam.activeName == '判断题' " @onSubmit="onSubmit" @onClose="onClose"/>
        </el-tab-pane>
        <el-tab-pane :disabled="$store.state.exam.edit.name  != '填空题' && $store.state.exam.edit.name  != ''  "
                     label="填空题"
                     name="填空题">
          <tian v-if="$store.state.exam.activeName == '填空题' " @onSubmit="onSubmit" @onClose="onClose"/>
        </el-tab-pane>
        <el-tab-pane :disabled="$store.state.exam.edit.name  != '简答题' && $store.state.exam.edit.name  != ''  "
                     label="简答题"
                     name="简答题">
          <jieda v-if="$store.state.exam.activeName == '简答题' " @onSubmit="onSubmit" @onClose="onClose"/>
        </el-tab-pane>
        <el-tab-pane :disabled="$store.state.exam.edit.name  != '扫码题' && $store.state.exam.edit.name  != ''  "
                     label="扫码题"
                     name="扫码题">
          <saoma v-if="$store.state.exam.activeName == '扫码题' " @onSubmit="onSubmit" @onClose="onClose"/>
        </el-tab-pane>
        <el-tab-pane :disabled="$store.state.exam.edit.name  != '阅读题' && $store.state.exam.edit.name  != ''  "
                     label="阅读题"
                     name="阅读题">
          <read v-if="$store.state.exam.activeName == '阅读题' " @onSubmit="onSubmit" @onClose="onClose"
                @readSelectType="readSelectType"/>
        </el-tab-pane>
      </el-tabs>

    </el-dialog>
    <!--    end-->
  </div>
</template>

<script>
let _this;
import crypto from "../../../utils/crypto";
import dan from '../examType/dan/dan';
import duo from '../examType/duo/duo';
import pan from '../examType/pan/pan';
import tian from '../examType/tian/tian';
import jieda from '../examType/jieda/jieda';
import saoma from '../examType/saoma/saoma';
import read from '../examType/read/read';

export default {
  components: {dan, duo, pan, tian, jieda, saoma, read},
  data() {
    return {
      searchParams: {},//搜索对象
      edite: '单选题',
      activeName: '单选题',
      loading: true,
      row: null, //当前选择数据
      ruleForms: {
        title: {label: "题目名称", prop: "title", type: "text"},
        paper_name: {label: "试卷名称", prop: "paper_name", type: "text"},
        type: {
          label: "类型", prop: "types", type: "select", select: [{label: '单选题', value: '单选题'},
            {label: '多选题', value: '多选题'},
            {label: '判断题', value: '判断题'},
            {label: '填空题', value: '填空题'},
            {label: '简答题', value: '简答题'},
            {label: '扫码题', value: '扫码题'},
            {label: '阅读题', value: '阅读题'}]
        },
        pattern: {
          label: "题目类型",
          prop: "pattern",
          type: "select",
          select: [{label: '作业', value: '0'}, {label: '考试', value: '1'}]
        },
      },
      pagination: {
        currentPage: 1,
        pageSize: 20,
        pageSizes: [10, 20, 50, 100],
      }, //分页参数
      otherParam: {
        halfCheckedKeys: [],
      }, //如果有其他情况会拼接这个参数

      dialogVisible: false,
      alertTitle: "添加",
      tableData: [],
      options: {
        uploadUrl: 'http://www.free.com/adminapi/v1.excel.ExcelOutEnter/excelEnterQuestion',
        buttonExcel:'导入',
        fields: {
          id: {label: "ID", prop: "id", width: "120", order: true},
          title: {label: "题目", prop: "title"},
          show_type: {label: "题目显示类型", prop: "show_type"},
          type: {label: "题目类型", prop: "type"},
          pattern: {label: "考试/作业", prop: "pattern"},
          score: {label: "分数", prop: "score", type: 'tag'},
          paper_name: {label: "试卷名称", prop: "paper_name"},
          A: {label: "A", prop: "A"},
          B: {label: "B", prop: "B"},
          C: {label: "C", prop: "C"},
          D: {label: "D", prop: "D"},
          E: {label: "E", prop: "E"},
          F: {label: "F", prop: "F"},
          dan: {label: "单选答案", prop: "dan"},
          duo: {label: "多选答案", prop: "duo"},
          pan: {label: "判断答案", prop: "pan"},
          tian: {label: "填空答案", prop: "tian"},
          content: {label: "简答/扫码答案", prop: "content"},
          json: {label: "阅读答案", prop: "json"},
          create_time: {label: "创建时间", prop: "create_time", order: true},
          button: {
            label: "操作",
            width: "130",
            type: "func",
            fixed: true,
            edit: function (scope) {
              _this.dialogVisible = true;
              _this.row = scope["row"];
              _this.alertTitle = "编辑";
              _this.$store.commit('exam/setRead', {type: 0, name: scope['row']['type']});
              _this.$store.commit('exam/setActionName', scope['row']['type']);
              if (scope['row']['type'] == '单选题') {
                _this.$store.commit('exam/setDan', {
                  title: scope['row']['title'],
                  score: scope['row']['score'],
                  pattern: scope['row']['pattern'],
                  paper_name: scope['row']['paper_name'],
                  show_type: scope['row']['show_type'],
                  type: scope['row']['type'],
                  answer: scope['row']['dan'],
                  A: scope['row']['A'],
                  B: scope['row']['B'],
                  C: scope['row']['C'],
                  D: scope['row']['D'],
                  E: scope['row']['E'],
                  F: scope['row']['F'],
                });
              } else if (scope['row']['type'] == '多选题') {
                _this.$store.commit('exam/setDuo', {
                  title: scope['row']['title'],
                  score: scope['row']['score'],
                  pattern: scope['row']['pattern'],
                  paper_name: scope['row']['paper_name'],
                  show_type: scope['row']['show_type'],
                  type: scope['row']['type'],
                  answer: scope['row']['duo'] == '' ? [] : scope['row']['duo'].split(','),
                  A: scope['row']['A'],
                  B: scope['row']['B'],
                  C: scope['row']['C'],
                  D: scope['row']['D'],
                  E: scope['row']['E'],
                  F: scope['row']['F'],
                });
              } else if (scope['row']['type'] == '判断题') {
                _this.$store.commit('exam/setPan', {
                  title: scope['row']['title'],
                  score: scope['row']['score'],
                  pattern: scope['row']['pattern'],
                  paper_name: scope['row']['paper_name'],
                  show_type: scope['row']['show_type'],
                  type: scope['row']['type'],
                  answer: scope['row']['pan'],
                });
              } else if (scope['row']['type'] == '填空题') {
                _this.$store.commit('exam/setTian', {
                  title: scope['row']['title'],
                  score: scope['row']['score'],
                  pattern: scope['row']['pattern'],
                  paper_name: scope['row']['paper_name'],
                  show_type: scope['row']['show_type'],
                  type: scope['row']['type'],
                  answer: scope['row']['tian'] == '' ? [] : scope['row']['tian'].split(','),
                });
              } else if (scope['row']['type'] == '简答题') {
                _this.$store.commit('exam/setJieDa', {
                  title: scope['row']['title'],
                  score: scope['row']['score'],
                  pattern: scope['row']['pattern'],
                  paper_name: scope['row']['paper_name'],
                  show_type: scope['row']['show_type'],
                  type: scope['row']['type'],
                  answer: scope['row']['content'],
                });
              } else if (scope['row']['type'] == '扫码题') {
                _this.$store.commit('exam/setSaoMa', {
                  title: scope['row']['title'],
                  score: scope['row']['score'],
                  pattern: scope['row']['pattern'],
                  paper_name: scope['row']['paper_name'],
                  show_type: scope['row']['show_type'],
                  type: scope['row']['type'],
                  answer: scope['row']['content'],
                });
              } else if (scope['row']['type'] == '阅读题') {
                _this.$store.commit('exam/setReadVlaue', {
                  title: scope['row']['title'],
                  score: scope['row']['score'],
                  pattern: scope['row']['pattern'],
                  paper_name: scope['row']['paper_name'],
                  show_type: scope['row']['show_type'],
                  type: scope['row']['type'],
                  answer: JSON.parse(scope['row']['json']),
                });
                _this.$store.commit('exam/setReadListValue', JSON.parse(scope['row']['json']))
              }
            },
            del: function (scope) {
              _this.deleteDate(scope["row"].id);
            },
          },
        },
      },
    };
  },
  methods: {



    downloadTemplate:function (){
      window.location.href = 'http://www.free.com/adminapi/v1.exam.ExamQuestion/downloadTemplate'
    },

    onUploadSuccess:function (){
      this.$message.success('导入成功');
      _this.getDateList(_this.searchParams);
    },
    onUploadError:function (){
      this.$message.error('导入失败');
    },
    resetForm: function () {
      _this.searchParams = {};
    },

    onClose: function () {
      if (this.$store.state.exam.edit.type == 0) {
        this.dialogVisible = false;
      } else {
        this.$store.commit('exam/setRead', {type: 1, name: ''});
        this.$store.commit('exam/setActionName', '阅读题');
      }
    },

    handleClick: function (tab) {

    },

    readSelectType: function (val) {
      this.$store.commit('exam/setActionName', val.types);
      this.$store.commit('exam/setRead', {type: 1, name: val.types});
    },

    handlePaginationCurrentChange: function (val) {
      _this.loading = true;
      _this.pagination["currentPage"] = val;
      _this.getDateList(_this.searchParams);
    },

    handlePaginationSizeChange: function (val) {
      _this.loading = true;
      _this.pagination["pageSize"] = val;
      _this.getDateList(_this.searchParams);
    },

    /**
     * 查询所有专业数据
     */
    getDateList: function (param) {
      _this.loading = true;
      _this.$store
        .dispatch("exam/getQuestionList", param ? {
          title: param['title'],
          type: param['types'],
          pattern: param['pattern'],
          paper_name: param['paper_name'],
          page: _this.pagination["currentPage"],
          pageSize: _this.pagination["pageSize"],
        } : {
          page: _this.pagination["currentPage"],
          pageSize: _this.pagination["pageSize"],
        })
        .then(() => {
          _this.loading = false;
          let data = this.$store.state.exam.questionList;
          let param = [];
          if (data.data) {
            data.data.forEach(item => {
              if (item.dan) item.dan = crypto.decrypt(item.dan);
              if (item.duo) item.duo = crypto.decrypt(item.duo);
              if (item.pan) item.pan = crypto.decrypt(item.pan);
              if (item.tian) item.tian = crypto.decrypt(item.tian);
              if (item.content) item.content = crypto.decrypt(item.content);
              if (item.json) item.json = crypto.decrypt(item.json);
              param.push(item);
            })
          }
          this.tableData = param;
          _this.pagination["currentPage"] = data["current_page"];
          _this.pagination["total"] = data["total"];
        });
    },


    /**
     * 批量删除
     */
    handleHeardDel: function (val) {
      let del = [];
      val.forEach((item, index) => {
        del.push(item.id);
      });
      _this.deleteDate(del);
    },


    addDate: function (param) {
      _this.$store
        .dispatch("office/addMajorList", {
          title: param["title"],
          level: param["level"],
          major_code: param["major_code"],
        })
        .then((res) => {
          const {data, msg} = res;
          if (data) {
            _this.$message.success(msg);
            _this.getDateList();
          } else {
            _this.$message.error(msg);
          }
        });
    },

    /**
     * 表单提交回调
     */
    onSubmit: function (param) {
      if (this.$store.state.exam.edit.type == 1) {//阅读跳转的
        this.$store.commit('exam/setRead', {type: 1, name: ''});
        this.$store.commit('exam/setActionName', '阅读题');
        return;
      }
      _this.$store.dispatch('exam/createQuestionOrUpdate',
        _this.isTypeReObj(param)).then((res) => {
        const {data, msg} = res;
        if (data) {
          _this.getDateList();
          if (_this.$store.state.exam.edit.type == 0 && _this.$store.state.exam.edit.name == '') {
            _this.$message.success(msg);
          } else {
            _this.$message.success(msg);
            _this.dialogVisible = false;
          }
        } else {
          _this.$message.error(msg);
        }
      })

    },

    isTypeReObj: function (param) {
      let base = {
        id: _this.row == null ? '' : _this.row.id,
        title: param['title'],
        show_type: param['show_type'],
        type: param['type'],
        pattern: param['pattern'],
        score: param['score'],
        paper_name: param['paper_name'],
        A: param['A'],
        B: param['B'],
        C: param['C'],
        D: param['D'],
        E: param['E'],
        F: param['F'],
        lenght: param['lenght'],
      }
      switch (_this.$store.state.exam.activeName) {
        case '单选题':
          let dan = {
            dan: param['answer'],
          }
          return Object.assign(base, dan);
        case '多选题':
          let duo = {
            duo: param['answer'],
          }
          return Object.assign(base, duo)
        case '判断题':
          let pan = {
            pan: param['answer'],
          }
          return Object.assign(base, pan)
        case '填空题':
          let tian = {
            tian: param['answer'],
          }
          return Object.assign(base, tian)
        case '简答题':
          let jianda = {
            content: param['answer'],
          }
          return Object.assign(base, jianda)
        case '扫码题':
          let saoma = {
            content: param['answer'],
          }
          return Object.assign(base, saoma)
        case '阅读题':
          let json = {
            json: param['answer'],
          }
          return Object.assign(base, json)
      }

    },

    /**
     * 搜索角色标题
     */
    searchForm: function (val) {
      _this.searchParams = val;
      _this.loading = true;
      _this.getDateList(val);
    },
    /**
     * 更新角色
     */
    updateDate: function (param) {
      _this.$store
        .dispatch("office/updateMajorList", {
          id: _this.row["id"],
          title: param["title"],
          level: param["level"],
          major_code: param["major_code"],
        })
        .then((res) => {
          const {data, msg} = res;
          if (data) {
            _this.getDateList();
            _this.$message.success(msg);
            return;
          }
          return _this.$message.error(msg);
        });
    },

    /**
     * 删除角色
     */
    deleteDate: function (val) {
      _this.$store
        .dispatch("exam/deleteQuestion", {
          id: val,
        })
        .then((res) => {
          const {data, msg} = res;
          if (data) {
            _this.getDateList();
            _this.$message.success(msg);
            return;
          }
          return _this.$message.error(msg);
        });
    },

    /**
     *  表单导航栏添加点击
     */
    handleAdd: function () {
      _this.alertTitle = "添加";
      _this.$store.commit('exam/setRead', {type: 0, name: ''})
      _this.$store.commit('exam/setActionName', '单选题');
      _this.dialogVisible = true;
      _this.row = null;
    },
  },

  created() {
    _this = this;
  },
  mounted() {
    this.getDateList();
  },
};
</script>

<style scoped>

</style>
